<!-- 电费充值 -->
<template>
    <div :class="`electricityCharge ${!isNan ? 'guoBg' : 'nanBg'}`">
        <van-nav-bar title="电费充值" right-text="查询记录" @click-right="onClickRight" left-arrow :border="false" @click-left="onClickLeft"/>
        <div class="head">
            <div class="flex alignCenter justifyBetween">
                <div class="headLabel">缴费单位</div>
                <div class="headRight flex alignCenter" @click="showArea = true">
                    <span v-if="province == ''">请选择</span>
                    <div v-else>{{province}}-{{city}}</div>
                    <van-icon style="margin-left: 8px" name="arrow" color="#ACACAC" size="15px"/>
                </div>
            </div>
            <div class="flex alignCenter">
                <div class="headLabel">缴费号码</div>
                <div class="headRight allFlex">
                    <van-field input-align="right" v-model="account" type="tel" placeholder="请输入缴费号码" />
                </div>
            </div>
            <div class="flex alignCenter">
                <div class="headLabel">标签</div>
                <div style="padding-left: 70px" class="headRight allFlex flex alignCenter justifyAround">
                    <div @click="electricType = item.id" :class="`electricType ${item.id == electricType ? 'active' : ''}`" v-for="item in electricTypeList" :key="item.id">{{item.name}}</div>
                </div>
            </div>
            <div class="flex alignCenter" v-if="isNan">
                <div class="headLabel">身份证后六位</div>
                <div class="headRight allFlex">
                    <van-field input-align="right" v-model="idCardNo" type="tel" placeholder="请输入身份证号码后六位" />
                </div>
            </div>
        </div>
        <!-- 产品模块展示 -->
        <div class="content flex justifyBetween" v-if="productList.length > 0">
            <div @click="selProduct(item)" class="productItem flex flexColumn alignCenter justifyCenter" v-for="item in productList" :key="item.id">
                <div class="facePrice"><span>{{item.facePrice}}</span>元</div>
                <div>售价{{item.price}}元</div>
                <div>{{item.description}}</div>
            </div>
        </div>
        <div v-else class="content flex justifyBetween alignCenter">
            <div>暂无充值面额</div>
        </div>
        <!-- 充值渠道 -->
        <div class="channel">
            <div @click="changeChannel(item)" class="channelItem flex alignCenter justifyBetween" v-for="item in channelList" :key="item.id">
                <div class="flex alignCenter"><img :src="item.icon" alt="">{{item.name}}</div>
                <img v-if="item.id == activeChannel" class="activeIcon" src="@/assets/lifePayCost/activeIcon.png" alt="">
                <img v-else src="@/assets/lifePayCost/unActiveIcon.png" alt="">
            </div>
        </div>
        <!-- 温馨提示 -->
        <div class="desc">
            <div class="descHead flex alignCenter"><span />充值须知 <i>请务必仔细阅读以下 条例后，再进行充值</i></div>
            <div class="descItem">
                <!-- <span>[到账时间] </span>电费慢充/平均1-5天区间到账 -->
                
            </div>
            <div class="descItem">
                <span>[提醒事项] </span>欠费100以内
            </div>
            <div class="descItem">
                <span>[提醒事项] </span>不支持区域：北京，上海，四川，港澳台，内蒙古，新疆。
            </div>
            <!-- <div class="descItem">
                <span>[提醒事项] </span>单户建议日缴8000月缴60000
            </div>
            <div class="descItem">
                <span>[提醒事项] </span>缴费金额建议大于欠费的金额
            </div> -->
        </div>
        <!-- 充值须知 -->
        <div class="desc">
            <div class="descHead flex alignCenter"><span />充值须知</div>
            <div class="descItem">
                1.不支持持电卡非智能电表用户该缴费业务
            </div>
            <div class="descItem">
                2.电费充值日常24小时内到账，高峰期48-72小时内到账，超时未到账全额退款，急用勿下单;
            </div>
            <div class="descItem">
                3.下单后，系统会自动提交充值，人工无法干预退款或更改订单，请您仔细核对地区及户号，充错概不负责;
            </div>
            <div class="descItem">
                4.首次充值金额需大于欠款金额，如单户欠费金额为201元，需要充值300元，充值200会导致失败;
            </div>
            <div class="descItem">
                5.国网电费欠款金额超过500，有可能导致充值失败，充值前请先确定当前户号的所剩余额;
            </div>
            <div class="descItem">
                6.缴费可能存在分批到账，48小时后可在“网上国网APP"软件上、“支付宝或微信的生活缴费专区"查询到账情况和余额;
            </div>
            <div class="descItem">
                7.充值成功后，可到当地电业局开具对应额度的发票;9.电费折扣存在浮动，具体以付款时显示的价格为准。
            </div>
        </div>

        <!-- 省市选择 -->
        <Area ref="areas" :showArea="showArea" @provinceChange="provinceChange" />

        <!-- 客服 -->
        <lifePayCostService></lifePayCostService>
    </div>
</template>

<script>
import { ref, reactive , getCurrentInstance, provide } from 'vue'
import storage from 'store';
import { Field , CellGroup , Icon , NavBar } from 'vant';
import { getOperator , getUserAgent } from '@/utils';
import { userAgent } from '@/utils/types';
import { ACCESS_TOKEN , BRANDID , ACCESS_TOKEN_BRAND } from '@/utils/types';
import Area from '@/components/Area';
import { dataEncryption , delNoneParameter } from '@/utils';
import qs from 'qs'
import lifePayCostService from '@/components/lifePayCostService';
export default {
    components: {
        [Field.name]: Field,
        [CellGroup.name]: CellGroup,
        [Icon.name]: Icon,
        [NavBar.name]: NavBar,
        Area,
        lifePayCostService,
    },
    setup() {
        const { proxy } = getCurrentInstance();
        console.log(proxy.$route.params)
        const appId = storage.get('appId')
        const brandId = storage.get(BRANDID)
        // 返回上一页
        const onClickLeft = () => history.back();
        // 跳转查询记录
        const onClickRight = () => proxy.$router.push({name: 'lifePayCostBillBefore',params: {'orderType': 3}});

        const getConfig = () =>{
            let url = window.location.href.split('#')[0]
            // alert(url,'url')
            // var url = 'https://szk.lexiangaysh.cn/'
            proxy.$http.externalApi.queryWxConfig(url,storage.get(BRANDID))
            .then(res=>{
                if(res.success){
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: appId, // 必填，公众号的唯一标识
                        timestamp: Number(res.data.timestamp), // 必填，生成签名的时间戳
                        nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                        signature: res.data.signature,// 必填，签名
                        jsApiList: ['updateAppMessageShareData','chooseWXPay'], // 必填，需要使用的JS接口列表
                    })
                }
            })
        }
        // 用户终端
        const userAgents = getUserAgent()
        if(userAgents == userAgent.WECHAT){
            getConfig();
        }

        // 省市信息
        const province = ref('');
        const city = ref('');
        const showArea = ref(false)
        const provinceChange = (val) =>{
            console.log(val,'获取子组件数据')
            if(val.length > 0){
                province.value = val[0].name.replace('省','').replace('市','').replace('宁夏回族自治区','宁夏').replace('内蒙古自治区','内蒙古').replace('广西壮族自治区','广西').replace('西藏自治区','西藏').replace('新疆维吾尔自治区','新疆')
                city.value = val[1].name.replace('省','').replace('市','')
                if(nanList.indexOf(province.value) != -1){
                    isNan.value = true;
                    operator.value = 5;
                }else{
                    isNan.value = false;
                    operator.value = 4;
                    idCardNo.value = '';
                }
            }
        }
        provide('showArea',showArea)
        provide('columnsNum',2)

        // 商户号
        const merchantNo = storage.get('merchantNo');
        // 版本信息
        const edition = proxy.$route.params.edition;
        // 运营商（默认国家电网）
        const operator = ref('4');
        const company = ref('国家电网');
        // 缴费号码
        const account = ref('')
        // 电费类型
        const electricType = ref('1');
        const electricTypeList = [
            { 'id': '1', 'name': '住宅'},
            { 'id': '2', 'name': '店铺'},
            { 'id': '3', 'name': '企业'},
        ];
        // 身份证后六位
        const idCardNo = ref(''); // 南网必传
        // 南网省份
        const nanList = ['广东省','广西壮族自治区','云南省','贵州省','海南省','香港特别行政区','澳门特别行政区'];
        const isNan = ref(false);

        // 获取充值产品
        const productList = ref([]);
        const getProduct = () =>{
            proxy.$http.externalApi.newQueryExternalReleaseProductInfo({merchantNo: merchantNo,edition: edition,operator: operator.value,classificationId: 3,province: province.value})
            .then(res=>{
                if(res.success){
                    var list = [];
                    productList.value = res.data.reduce((arr,item) =>{
                        console.log(item,'item')
                        if(brandId != 7){
                            if(item.facePrice < 201){
                                arr.push(item);
                            }
                        }else{
                            arr.push(item)
                        }
                        return arr;
                    },[]);
                }else{
                    proxy.$toast({position: 'bottom',message:res.errMessage})
                }
            })
        }
        getProduct();

        // 选择充值渠道
        const activeChannel = ref(2);
        const channelList = [
            { 'id': 1, 'name': '支付宝', 'icon': require('../../assets/lifePayCost/zhfbIcon.png')},
            { 'id': 2, 'name': '微信', 'icon': require('../../assets/lifePayCost/wxIcon.png')},
        ];
        const changeChannel = (item) =>{
            activeChannel.value = item.id;
        }

        const confirmProduct = (item) =>{
            proxy.$http.externalApi.newElectricRechargePlaceOrder({merchantNo: merchantNo,account: account.value,productId: item.productId,electricType:electricType.value,province: province.value,city: city.value,idCardNo: idCardNo.value})
            .then(async res=>{
                if(res.success){
                    if(userAgents == userAgent.WECHAT){
                        if(activeChannel.value == 2){
                            var openId = await getOpenId();
                            pay(res.data,{openId: openId})
                        }else{
                            const params = {
                                'merchantNo': merchantNo,
                                'orderCode': res.data,
                                'payType': activeChannel.value,
                            }
                            const objPar = delNoneParameter(Object.assign(qs.parse(qs.stringify(params)),dataEncryption(qs.parse(qs.stringify(params)))))
                            let paramsArr = new Array()
                            // console.log(dataObj)
                            Object.keys(objPar).sort().map(function(key){
                                // 判断key值的类型，文件的过滤掉
                                if(typeof(objPar[key]) != 'object'  && objPar[key] !== "" && objPar[key] != undefined){
                                    paramsArr.push(
                                    key + '=' + objPar[key]
                                    )
                                }
                            })
                            let paramsStr = paramsArr.join('&')
                            var url = `https://${window.location.host}${process.env.VUE_APP_API_BASE_URL}/open/api/promotion/recharge/pay?${paramsStr}`;
                            proxy.$router.push({name: 'gathering', params: {'title': '支付宝支付','money': item.price, 'url': url}})
                        }
                    }else{
                        pay(res.data,{openid: undefined})
                    }
                }else{
                    proxy.$toast({position: 'bottom',message:res.errMessage})
                }
            })
        }

        // 选择充值产品
        const selProduct = (item) =>{
            console.log(item.edition,'item')
            // proxy.$toast({message: '商户额度已满，暂时无法充值！',position: 'bottom'})
            // return;
            if(province.value == ''){
                proxy.$toast({message: '请选择充值省份！',position: 'bottom'})
                return;
            }
            if(account.value == ''){
                proxy.$toast({message: '充值账号不能为空！',position: 'bottom'})
                return;
            }
            if(isNan.value){
                if(idCardNo.value == '' || idCardNo.value.length != 6){
                    proxy.$toast({message: '请输入正确的身份证号码后六位！',position: 'bottom'})
                    return;
                }
            }
            // 如果是在微信，无法使用支付宝，否则无法使用微信支付
            // if(userAgents == userAgent.WECHAT && activeChannel.value == 1){
            //     proxy.$toast({message: '微信内无法使用支付宝支付，请更换支付方式',position: 'bottom'})
            //     return;
            // }
            if(userAgents !== userAgent.WECHAT && activeChannel.value == 2){
                proxy.$toast({message: '微信支付必须要在微信浏览器内支付，请更换其他支付方式',position: 'bottom'})
                return;
            }
            proxy.$dialog.confirm({
                title: '温馨提示',
                message: `请确认充值账号：${account.value} ，充值金额 ${item.facePrice} 元？`,
            }).then(()=>{confirmProduct(item);})
        }
        // 支付
        const pay = (orderCode,{openId = ''}) =>{
            proxy.$http.externalApi.promotionRechargePay({merchantNo: merchantNo,orderCode: orderCode,payType: activeChannel.value,openId: openId})
            .then(res=>{
                if(userAgents != userAgent.WECHAT){
                    var div = document.createElement('div')
                    div.innerHTML = res
                    document.body.appendChild(div)
                    document.forms[0].submit()
                }else{
                    if(res.success){
                    // 微信下需要掉起微信支付，微信外处理支付宝返回数据
                    if(userAgents == userAgent.WECHAT){
                        var resData = JSON.parse(res.data)
                        console.log(resData,'resData')
                        // alert(resData)
                        wx.chooseWXPay({
                            timestamp: resData.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                            nonceStr: resData.nonceStr, // 支付签名随机串，不长于 32 位
                            package: resData.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                            signType: resData.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                            paySign: resData.paySign, // 支付签名
                            appId: resData.appId,
                            success: function (res) {
                                // 支付成功后的回调函数
                                proxy.$toast({message: '支付成功',position: 'bottom'})
                            },
                        });
                    }else{
                        
                    }
                }else{
                    proxy.$toast({position: 'bottom',message:res.errMessage})
                }
                }
            })
        }
        // 微信支付需要获取用户的OpenId
        const getOpenId = () =>{
            return new Promise((resolve,reject) =>{
                proxy.$http.externalApi.queryWxOpenId({code: storage.get('code'),brandId: storage.get(BRANDID)})
                .then(res=>{
                    if(res.success){
                        resolve(res.data.openid)
                    }else{
                        proxy.$toast({position: 'bottom',message:res.errMessage})
                    }
                })
            })
        }

        

        return{
            onClickLeft,
            onClickRight,
            productList,
            operator,
            channelList,
            activeChannel,
            changeChannel,
            selProduct,
            province,
            city,
            provinceChange,
            showArea,
            electricTypeList,
            electricType,
            isNan,
            account,
            idCardNo,
        }
    }
}

</script>
<style scoped>
.electricityCharge{
    min-height: 100vh;
    /* padding-top: 12px; */
    box-sizing: border-box;
}
.guoBg{
    background: url('../../assets/lifePayCost/electricityChargeHeadGuoBg.png') no-repeat;
    background-size: 100%;
    background-repeat: no-repeat;
}
.nanBg{
    background: url('../../assets/lifePayCost/electricityChargeHeadNanBg.png') no-repeat;
    background-size: 100%;
    background-repeat: no-repeat;
}
.electricityCharge /deep/ .van-nav-bar{
    background: none;
}
.electricityCharge /deep/ .van-icon{
    color: #FFFFFF;
}
.electricityCharge /deep/ .van-nav-bar__title{
    color: #FFFFFF;
}
.electricityCharge /deep/ .van-nav-bar__text{
    color: #FFFFFF;
}
/* 头部输入内容 */
.head{
    margin: 0 12px 10px;
    border-radius: 8px;
    background: #FFFFFF;
    padding: 10px 10px;
}
.head>div{
    height: 55px;
}
.headLabel{
    font-size: 15px;
    color: #333333;
}
.headLabel::after{
    content: '*';
    color: red;
}
.headRight span{
    font-size: 15px;
    color: #ACACAC;
}
.electricType{
    width: 51px;
    height: 25px;
    border-radius: 13px;
    text-align: center;
    color: #666666;
    font-size: 15px;
    line-height: 25px;
    background: #DFEEFF;
}
.electricType.active{
    color: #FFFFFF;
    background: var(--themeColor);
}

/* 产品模块展示 */
.content{
    margin: 10px 12px;
    border-radius: 8px;
    background: #FFFFFF;
    flex-wrap: wrap;
    padding: 22px 10px;
}
.productItem{
    width: 105px;
    height: 92px;
    background: #F7FBFF;
    border-radius: 5px;
    font-size: 12px;
    color: #888888;
}
.facePrice{
    font-size: 15px;
    color: var(--themeColor);
}
.facePrice span{
    font-size: 25px;
    font-weight: bold;
}
/* 充值渠道 */
.channel,.desc{
    margin: 10px 12px;
    border-radius: 8px;
    background: #FFFFFF;
    padding: 10px 20px;
}
.channelItem{
    height: 45px;
    font-size: 15px;
    color: #333333;
}
.channelItem img{
    width: 18px;
    height: 18px;
    margin-right: 10px;
    display: inline-block;
}
/* 充值须知 */
.descHead{
    font-size: 15px;
    font-weight: 500;
    color: #333333;
}
.descHead span{
    height: 14px;
    width: 3px;
    background: linear-gradient(to top, #2184F8 , #FFFFFF);
    margin-right: 10px;
}
.descItem{
    font-size: 13px;
    color: #666666;
    margin: 5px 0;
}
.descItem span{
    color: var(--themeColor);
}
.desc i{
    font-style: normal;
    color: #FFAE3B;
    font-size: 13px;
}
</style>